package com.jkl.nettyserver.Web.Controller;

import com.jkl.entity.*;
import com.jkl.nettyserver.Netty.General;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
@Controller
@Slf4j
public class AppController {
    @PostMapping("/sendMessage")
    public ResponseEntity<RMessage> sendMessage(@RequestBody Message message) {
        try {
            log.info("收到WebSocket文本消息：{}", message);
            Channel receiverChannel = General.CHANNEL_MAP.get(message.getReceiver());
            // 转发消息
            if (receiverChannel != null) {
                receiverChannel.writeAndFlush(new TextWebSocketFrame(General.gson.toJson(message)));
            }
            return ResponseEntity.ok().body(new RMessage(message));
        } catch (Exception e) {
            log.error("发送消息时出错", e);
            return ResponseEntity.status(500).build();
        }
    }
    @PostMapping("/sendApplication")
    public ResponseEntity<Void> sendApplication(@RequestBody CSApplication application){
        try {
            log.info("收到申请信息：{}",application);
            Channel receiverChannel = General.CHANNEL_MAP.get(application.getFriendId());
            if (receiverChannel != null) {
                receiverChannel.writeAndFlush(new TextWebSocketFrame(General.gson.toJson(new SCApplication(application))));
            }
            return ResponseEntity.ok().build();
        }catch (Exception e) {
            log.error("发送消息时出错", e);
            return ResponseEntity.status(500).build();
        }
    }

    @PostMapping("/sendAgreeApplication")
    public ResponseEntity<Void> sendAgreeApplication(@RequestBody SCAgree agree){
        try {
            log.info("收到申请信息：{}",agree);
            Channel receiverChannel = General.CHANNEL_MAP.get(agree.getUserId());
            if (receiverChannel != null) {
                agree.userId=null;
                receiverChannel.writeAndFlush(new TextWebSocketFrame(General.gson.toJson(agree)));
            }
            return ResponseEntity.ok().build();
        }catch (Exception e) {
            log.error("发送消息时出错", e);
            return ResponseEntity.status(500).build();
        }
    }
}
